package com.tanxi521.tnweb.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.tanxi521.tnweb.model.*;
import com.tanxi521.tnweb.service.PlayerAccountService;
import com.tanxi521.tnweb.service.VipPlayersService;
import com.tanxi521.tnweb.service.WebUserService;
import com.tanxi521.tnweb.utils.FileUploadUtils;
import com.tanxi521.tnweb.utils.Result;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Random;

@Controller
public class UserController {

    @Autowired
    WebUserService webUserService;

    @Autowired
    PlayerAccountService playerAccountService;

    @Autowired
    VipPlayersService vipPlayersService;

    @RequestMapping("user/checkId")
    @ResponseBody
    public Object checkId(String userId) {
        Integer num = webUserService.checkId(userId);
        if (num == 1) {
            return Result.error("该账户已被注册");
        }
        return Result.success("该账户可用~");
    }

    @RequestMapping("code")
    public void verifyCode(HttpServletResponse response, HttpSession session) throws IOException {
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(140, 45, 4, 30);
        String code = captcha.getCode();
        session.setAttribute("code", code);
        ServletOutputStream outputStream = response.getOutputStream();
        captcha.write(outputStream);
        outputStream.close();
    }

    @RequestMapping("user/register")
    @ResponseBody
    public Object register(String userId, String password, String code, HttpSession session) {
        String correctCode = (String) session.getAttribute("code");
        if (!StringUtils.equals(code, correctCode)) {
            return Result.error("验证码不正确");
        }
        Integer num = webUserService.register(userId, password);
        if (num == 0) {
            return Result.error("系统繁忙，注册失败");
        }
        return Result.success("注册成功，2秒后跳转主页");
    }

    @RequestMapping("user/login")
    @ResponseBody
    public Object login(String userId, String password, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        WebUser user = webUserService.queryUsersByUserIdAndPassword(userId);
        if (!ObjectUtils.allNotNull(user)) {
            return Result.error("你还没有注册，或者系统繁忙，请稍后再试");
        }
        if (!StringUtils.equals(password, user.getUserPassword())) {
            return Result.error("用户名或密码错误");
        }
        if (user.getIsBound() == 0) {
            session.setAttribute("webUser", user);
            Date date = new Date();
            webUserService.modifyUserLastLoginTime(date, userId);
        }
        if (user.getIsBound() == 1) {
            int id = user.getMcId();
            PlayerAccount playerAccount = playerAccountService.queryPlayerByPlayerId(id);
            VipPlayers vipPlayers = vipPlayersService.queryPlayersByUserId(playerAccount.getRealname());
            session.setAttribute("webUser", user);
            session.setAttribute("playerAccount", playerAccount);
            session.setAttribute("vipPlayers", vipPlayers);
            Date date = new Date();
            webUserService.modifyUserLastLoginTime(date, userId);
        }
        return Result.success("登陆成功，2秒后跳转");
    }

    @RequestMapping("user/loginOut")
    public String logOut(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Object playerAccount = session.getAttribute("playerAccount");
        Object vipPlayers = session.getAttribute("vipPlayers");
        session.removeAttribute("webUser");
        if (ObjectUtils.allNotNull(playerAccount)) {
            session.removeAttribute("playerAccount");
        }
        if (ObjectUtils.allNotNull(vipPlayers)) {
            session.removeAttribute("vipPlayers");
        }
        Cookie cookie_username = new Cookie("cookie_username", "");
        cookie_username.setMaxAge(0);
        cookie_username.setPath(request.getContextPath());
        response.addCookie(cookie_username);
        return "redirect:/index";
    }

    @RequestMapping("user/boundMc")
    @ResponseBody
    public Object boundMc(String mcId, String mcPassword, HttpSession session) throws Exception {
        PlayerAccount account = playerAccountService.queryPlayerByPlayerName(mcId, mcPassword, session);
        if (!ObjectUtils.allNotNull(account)) return Result.error("该ID不存在，请先去游戏内注册");
        if (StringUtils.equals(account.getPassword(), "账号或密码错误")) return Result.error(account.getPassword());
        if (account.getHassession() == 0) return Result.error("该账户已被绑定");
        return Result.success("绑定成功，即将刷新页面");
    }

    @RequestMapping("user/getPlayerInfo")
    @ResponseBody
    public Object getPlayerInfo(String userId) {
        PlayerPageInfo playerPageInfo = playerAccountService.getPlayerInfo(userId);
        return playerPageInfo;
    }

    @RequestMapping("user/getPlayerInfoHead")
    @ResponseBody
    public Object getPlayerInfoHead(HttpSession session) {
        Integer id = (Integer) session.getAttribute("playerInfoId");
        if (id == 0) {
            PlayerPageInfoHead playerPageInfoHead = new PlayerPageInfoHead();
            playerPageInfoHead.setIsBound(0);
            playerPageInfoHead.setWebUserName("请先登陆");
            int i = new Random().nextInt(5) + 1;
            playerPageInfoHead.setWebUserHead("/tnweb/image/user_head/default_head" + i + ".png");
            return playerPageInfoHead;
        }
        WebUser webUser = webUserService.queryUserByUserId(id);
        PlayerPageInfoHead playerPageInfoHead = new PlayerPageInfoHead();
        playerPageInfoHead.setWebUserName(webUser.getUserId());
        if (webUser.getHeadImg() != null) {
            playerPageInfoHead.setWebUserHead(webUser.getHeadImg());
        } else {
            playerPageInfoHead.setWebUserHead("/tnweb/image/user_head/default_head.jpg");
        }
        WebUser loginUser = (WebUser) session.getAttribute("webUser");
        if (webUser.getIsBound() == 1) {
            playerPageInfoHead.setIsBound(1);
            PlayerAccount playerAccount = playerAccountService.queryPlayerByPlayerId(webUser.getMcId());
            playerPageInfoHead.setBoundMcName(playerAccount.getRealname());
            if (loginUser == null) {
                playerPageInfoHead.setIsMe(0);
            } else if (id == loginUser.getId()) {
                playerPageInfoHead.setIsMe(1);
            } else if (id != loginUser.getId()) {
                playerPageInfoHead.setIsMe(0);
            }
        } else {
            playerPageInfoHead.setIsBound(0);
            if (loginUser == null) {
                playerPageInfoHead.setBoundMcName("该玩家未绑定");
                playerPageInfoHead.setIsMe(0);
            } else if (id == loginUser.getId()) {
                playerPageInfoHead.setBoundMcName("未绑定，点击绑定");
                playerPageInfoHead.setIsMe(1);
            } else if (id != loginUser.getId()) {
                playerPageInfoHead.setBoundMcName("该玩家未绑定");
                playerPageInfoHead.setIsMe(0);
            }
        }
        return playerPageInfoHead;
    }

    @RequestMapping("user/unBoundMc")
    @ResponseBody
    public Object deBoundMc(HttpSession session, String mcPassword) {
        return playerAccountService.deBoundMc(session, mcPassword);
    }

    @RequestMapping("user/boundRewards")
    @ResponseBody
    public MailBoxFile boundRewards(HttpSession session) {
        PlayerAccount playerAccount = (PlayerAccount) session.getAttribute("playerAccount");
        String mcId = playerAccount.getRealname();
        MailBoxFile mailBoxFile = playerAccountService.giveBoundRewards(mcId);
        if (mailBoxFile == null) {
            MailBoxFile failed = new MailBoxFile();
            failed.setType("白嫖怪");
            failed.setDescriptions("你已经领取过了！害想白嫖呢？");
            return failed;
        }
        return mailBoxFile;
    }

    @RequestMapping("user/uploadHead")
    @ResponseBody
    public Object uploadHead(MultipartFile uploadHead, HttpServletRequest request) {
        HttpSession session = request.getSession();
        WebUser webUser = (WebUser) session.getAttribute("webUser");
        String userId = webUser.getUserId();
        Map<String, Object> result = FileUploadUtils.uploadHeadImg(uploadHead, userId);
        String code = (String) result.get(Result.CODE);
        String msg = (String) result.get(Result.MSG);
        if (StringUtils.equals("0", code)) return Result.error(msg);
        webUser.setHeadImg(msg);
        int num = webUserService.modifyWebUser(webUser);
        if (num == 0) {
            return Result.error("头像更新失败");
        } else {
            session.setAttribute("webUser", webUser);
        }
        return Result.success("头像更新成功");
    }
}
